package cn.itsource.ymcc.config;

import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;


@Configuration
@EnableWebSecurity//启动
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PermissionMapper permissionMapper;
    //提供用户信息，这里没有从数据库查询用户信息，在内存中模拟
//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager inMemoryUserDetailsManager =
//                new InMemoryUserDetailsManager();//管理当前登录用户的信息
//        //创建用户
//        inMemoryUserDetailsManager.createUser(
//                User.withUsername("zs")//账号
//                        .password("123")//密码
//                        .authorities("admin")//权限
//                        .build()
//        );
//        return inMemoryUserDetailsManager;
//    }

    //security默认是有密码加密规则的
    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();//不使用密码加密
        return new BCryptPasswordEncoder();
    }

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<Permission> permissionList = permissionMapper.selectList(null);
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.formLogin()                              //允许表单登录
                .successForwardUrl("/login/123")             // 设置登陆成功页  发送的是post请求  前后端分离是根本不需要这个东西
                .and().authorizeRequests()                                //授权配置
                .antMatchers("/login", "/login/list","/login/NoP").permitAll();

        for (Permission permission : permissionList) {
            expressionInterceptUrlRegistry = expressionInterceptUrlRegistry  //登录路径放行
                    .antMatchers(permission.getResource())
                    .hasAuthority(permission.getSn());
        }
        expressionInterceptUrlRegistry//需要什么权限
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查  可以提供效率
    }
}
